import { useEffect, useState } from "react"
import { detailsData, fetchDetails } from "@/apis/details"
import { useNavigate,  useSearchParams } from "react-router-dom"
import { NavBar } from "antd-mobile"

const Detail = () => {
  // 获取路由参数
  const [params] = useSearchParams()
  const id = params.get('id')
  const [detail, setDetail] = useState<detailsData | null>(null)
  useEffect(() => {
    const getDetail = async (id: string) => {
      try {
        const res = await fetchDetails(id)
        setDetail(res.data.data)
      } catch (error) {
        throw new Error('报错error')
      }
    }
    getDetail(id!)
  }, [id])


  // 返回上一层
  const navigate = useNavigate()
  const backClick = () => {
    navigate(-1)
  }

  // 数据返回之前 loading占位
  if(detail) {
    return <div>loading</div>
  }
 // 数据返回之后
  return (
    <>
      <div>
        <NavBar onBack={backClick()}>{detail?.title}</NavBar>
        {/* dangerouslySetInnerHTML 展示数据返回带有p标签的数据 */}
        <div dangerouslySetInnerHTML={{
          __html:detail?.content
        }}></div>
      </div>
    </>
  )
}
export default Detail